package com.qf.gh.web.filter;

import com.qf.gh.domain.User;
import com.qf.gh.service.UserService;
import com.qf.gh.service.impl.UserServiceImpl;
import com.qf.gh.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            filterChain.doFilter(request,response);
            return;
        }
        Cookie[] cookies = request.getCookies();
        if(cookies == null  || cookies.length == 0) {
            response.sendRedirect("/login.jsp");
            filterChain.doFilter(request, response);
            return;
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if("userinfo".equals(name)) {
                String value = cookie.getValue();
                String userInfo = Base64Utils.decode(value);
                String[] arr = userInfo.split("#");
                if(arr != null  && arr.length == 2) {
                    UserService userService = new UserServiceImpl();
                    User login = userService.login(arr[0], arr[1]);
                    if(login != null) {
                        request.getSession().setAttribute("user", login);
                        return;
                    }

                }

            }
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
